<template>
  <!-- 分摊动因 -->
  <div>
    <el-row class="ruleDriverList container">
      <el-col style="margin-right:10px;" class="content-left">
        <!-- 按钮与搜索 -->
        <el-row class="handleBox">
          <!-- 左侧按钮 -->
          <el-col :span="18">
            <el-button @click="clickBtn('1')">新增</el-button>
            <el-button @click="clickBtn('2')">编辑</el-button>
            <el-button @click="deleFunc()">删除</el-button>
            <el-button @click="clickBtn('3')">查看</el-button>
            <el-button @click="clickBtn('5')">复制</el-button>
            <el-button @click="refFunc()">引用情况</el-button>
            <el-button @click="dataShow()">数据展示</el-button>
          </el-col>
          <!-- 右侧查询图标 -->
          <el-col :span="6">
            <div class="handleIconBox">
              <!-- 查询弹框 -->
              <el-popover placement="left-start" trigger="click" popper-class="icon_porper">
                <div class="search_porper">
                  <el-form
                    :model="searchForm"
                    ref="searchForm"
                    label-width="100px"
                    label-position="right"
                    size="mini"
                  >
                    <el-form-item label="动因编码：" prop="driverCode">
                      <el-input v-model="searchForm.driverCode" style="width:150px"></el-input>
                    </el-form-item>
                    <el-form-item label="动因名称：" prop="driverName">
                      <el-input v-model="searchForm.driverName" style="width:150px"></el-input>
                    </el-form-item>
                    <el-form-item label="动因类型：" prop="driverType">
                    <el-select
                      v-model="searchForm.driverType"
                      style="width:150px"
                      placeholder="请选择"
                      
                    >
                      <el-option value="0" label="静态动因"></el-option>
                      <el-option value="1" label="动态动因"></el-option>
                    </el-select>
                    </el-form-item>
                  </el-form>
                  <div style="text-align:center;padding:10px">
                    <el-button size="mini" @click="searchFunc">查询</el-button>
                    <el-button
                      size="mini"
                      @click="
                        (searchForm.driverCode = ''), (searchForm.driverName = ''),(searchForm.driverType = '')
                      "
                    >重置</el-button>
                  </div>
                </div>
                <i class="iconfont icon-sousuo" title="搜索" slot="reference"></i>
              </el-popover>
              <!-- 字段展示弹框 -->
              <el-popover placement="bottom" width="150" trigger="click" popper-class="icon_porper">
                <div class="operation_checkbox">
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox
                      v-for="item in textData"
                      :label="item.label"
                      :key="item.prop"
                    >{{ item.label }}</el-checkbox>
                  </el-checkbox-group>
                </div>
                <i class="iconfont icon-liebiaoshezhi" title="列表设置" slot="reference"></i>
              </el-popover>
            </div>
          </el-col>
        </el-row>

        <!-- 列表 -->
        <el-table ref="multipleTable" :data="tableData" style="width: 100%" @row-click="rowClick">
          <el-table-column width="55" type="selection"  />

          <el-table-column prop="driverCode" label="动因编码" show-overflow-tooltip v-if="columnState[0]" />

          <el-table-column prop="driverName" label="动因名称 " show-overflow-tooltip v-if="columnState[1]" />

          <el-table-column
            prop="driverType"
            label="类型 "
            show-overflow-tooltip
            v-if="columnState[2]"
            :formatter="dictFormatter"
          ></el-table-column>

          <el-table-column
            prop="creator"
            label="创建人"
            show-overflow-tooltip
            sortable
            v-if="columnState[3]"
            :formatter="row => row.modifier || '-'"
          />

          <el-table-column prop="createdTm" label="创建时间" 
          :formatter=" row =>( row.createdTm ? timeFormat(row.createdTm) :'-')"
          show-overflow-tooltip sortable v-if="columnState[4]">
           
          </el-table-column>

          <el-table-column
            prop="modifier"
            label="修改人"
            show-overflow-tooltip
            sortable
            v-if="columnState[5]"
            :formatter="row => row.modifier || '-'"
          ></el-table-column>
          <el-table-column prop="modifiedTm" label="修改时间" 
           :formatter="row => (row.modifiedTm ? timeFormat(row.modifiedTm) :'-')"
           show-overflow-tooltip sortable v-if="columnState[6]">
          </el-table-column>
        </el-table>
        <!-- 分页插件 -->
        <pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.page"
          :page-size="searchForm.size"
          @refresh="searchFunc"
          :total="total"
        ></pagination>
      </el-col>
    </el-row>
    <!-- 新增,编辑,查看 form保单 -->

    <rule-form
      ref="ruleDriverForm"
      :editTheData="editTheData"
      :popupWindowType="popupWindowType"
      :dialogVisibleProps="dialogVisible"
      @getDialogVisible="getDialogVisible"
    ></rule-form>

    <!-- 新增,编辑,查看 form保单结束 -->

    <!-- 查看引用情况 -->
    <el-dialog v-dialogDrag title="引用情况" :visible.sync="refFalg" width="950px">
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane :label="tabPaneName" name="first">
          <el-row class="refqutoList container">
            <el-col style="margin-right:10px;" class="content-left">
              <!-- 按钮与搜索 -->
              <el-row class="handleBox">
                <!-- 左侧按钮 -->
                <el-col :span="24">
                  <!-- TODO 没有完成按钮 -->
                  <el-button @click="addOrEditFunc('5')">查看</el-button>
                </el-col>
                <!-- 右侧查询图标 -->
                <div></div>
              </el-row>

              <!-- 列表 -->
              <el-table ref="refmultipleTable" :data="refTableData" height="300"
               @row-click="refRowClick">
                <el-table-column width="35" type="selection"  />

                <el-table-column prop="ruleCode" show-overflow-tooltip label="规则编码" sortable />

                <el-table-column prop="ruleName" show-overflow-tooltip label="规则名称 " />

                <el-table-column prop="ruleType" show-overflow-tooltip label="规则类型" :formatter="refRuleTypeFormatter" sortable />

                <el-table-column prop="driverType" show-overflow-tooltip label="分摊方法" :formatter="refDictFormatter" sortable  />

                <el-table-column prop="descn" show-overflow-tooltip label="描述" />
              </el-table>
              <!-- 分页插件 -->
              <pagination
                @size-change="refhandleSizeChange"
                @current-change="refhandleCurrentChange"
                :current-page="refsearchForm.page"
                :page-size="refsearchForm.size"
                @refresh="refsearchFunc"
                :total="reftotal"
              ></pagination>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!-- 查看引用情况结束 -->
    <el-dialog
      v-dialogDrag
      title="查看"
      :visible.sync="addOrEdit"
      append-to-body
      width="65%"
      min-height="600px;"
      top="2%"
    >
      <!-- 引入公共组件 -->
      <ruleDefComponents
        :operateType="buttonType"
        :ruleCode="ruleCodeDef"
        @closeToQuery="closeToQuery"
        ref="childComponents"
      ></ruleDefComponents>
    </el-dialog>
    <!--   数据展示弹框  -->
    <el-dialog
      v-dialogDrag
      title="数据展示查看"
      :visible.sync="dataShowView"
      append-to-body
      width="65%"
      min-height="600px;"
      top="2%"
    >


    <div style="padding:10px 0">
     <el-button @click="exportFiles">导出</el-button>
    </div >
     <el-table 
        ref="dataShowMultipleTable"
        :data="dataShowTableList"
        @row-click="dataShowRowClick"
        style="width: 100%">
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>
          <el-table-column
            v-for="(item, index) in dataShowData"
             show-overflow-tooltip
            :key="index"
            :prop="item.columnEn.toUpperCase()"
            :label="item.columnCn"
          ></el-table-column>
        </el-table>
        <pagination
          @size-change="dataShowhandleSizeChange"
          @current-change="dataShowhandleCurrentChange"
          :current-page="dataShowSearchForm.page"
          @refresh="dataShowSearchFunc"
          :page-size="dataShowSearchForm.size"
          :total="dataShowTotal"
        ></pagination>
    </el-dialog>
    <!-- 静态数据展示弹窗 -->
     <el-dialog
      v-dialogDrag
      title="数据展示查看"
      :visible.sync="dataShowStaticView"
      append-to-body
      width="65%"
      min-height="600px;"
      top="2%"
    >
    <div style="padding:10px 0">
     <el-button v-if="xJson.length!=0&&yJson.length!=0" @click="exportStaticFiles">导出</el-button>
    </div >
    <div style="margin-bottom:20px;">
       <c-table :xJson="xJson" :yJson="yJson" :tableValue="tableValue" :readonly="dataShowStaticView" v-if="ctableShow" style="width:100%"></c-table>
  </div>

    </el-dialog>
    <!-- 静态数据展示弹窗 -->
  </div>
</template>


<script>
// 引入因子表格
import cTable from '@/components/ca/table/complexTable'
import { caRuleDriverApi } from "@/api/index";
// import onlyOneSearch from '@/components/onlyOneSearch'
import moment from "moment";
//跳转form表单
import ruleForm from "./ruleDriverFormManage";
//转换字典名称
import { getNameByCode } from "@/lib/util";
//获取字典数据
import { getDict } from "@/api/getDict";
//生成ca编码
import { pubSysparamList } from "@/api/index";

import ruleDefComponents from "@/components/ca/ruleDefComponents";

export default {
  data() {
    return {
      xJson: [],
      yJson: [],
      ctableShow: false,
      tableValue: [],
      //表单元素过滤
      textData: [
        { prop: "driverCode", label: "动因编码" },
        { prop: "driverName", label: "动因名称" },
        { prop: "driverType", label: "类型" },
        { prop: "creator", label: "创建人" },
        { prop: "createdTm", label: "创建时间" },
        { prop: "modifier", label: "修改人" },
        { prop: "modifiedTm", label: "修改时间" }
      ], //双向绑定 选择表单展示字段
      checkList: [],
      //查询时默认条件
      searchForm: {
        page: 1,
        size: 15,
        driverCode: "", 
        driverName: "",
        driverType: ""
      },
      total: 0,
      //表单提交时保存的数据
      saveFrom: {},
      //列表数据对象
      tableData: [
      ],
      //也签信息
      titleName: "",
      //按钮操作标识
      operateType: "1",
      //保存实体
      saveForm: {},
      //引用情况页面控制
      refFalg: false,
      //引用情况页面标签页
      activeName: "first",
      //页签
      tabPaneName: "规则定义(0)",
      //规则定义引用情况数据
      refTableData: [],
      //规则引入查询条件
      reftotal: 0,
      //查看引用时的分摊编码
      refdriverCode: "",
      //规则引用查询
      refsearchForm: {
        page: 1,
        size: 15
      },
      //  组件信息###############################################################################################
      //弹窗类型
      popupWindowType: "",
      //编辑数据
      editTheData: {},
      //弹窗开关
      dialogVisible: false,
      //新增查看弹框是否展示
      addOrEdit: false,
      buttonType: "",
      ruleCodeDef: "",
      // ####### 数据展示##########
      dataShowTableList:[],
      dataShowTotal:15,
      dataShowData:[],
      //数据展示弹框控制
      dataShowView : false,
      dataShowStaticView: false,
      dataShowSearchForm:{
        page:1,
        size:15
      },
      dataShowDriverCode:"",


    };
  },
  components: {
    // onlyOneSearch,
    ruleForm,
    ruleDefComponents,
    cTable
  },
  created() {
    this.checkListInit();
    console.log(this.tableData, "模拟数据");
  },
  computed: {
    columnState() {
      let arr = [],
        arr1 = this.textData,
        arr2 = this.checkList;
      for (let i = 0; i < arr1.length; i++) {
        let flag = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label == arr2[j]) {
            flag = true;
            break;
          }
        }
        arr.push(flag);
      }
      return arr;
    }
  },
  mounted() {
    this.searchFunc();
  },
  watch: {},
  methods: {
    // 数据展示导出
    exportFiles(){
      let params = {
        clomns: this.dataShowData,
        driverCode: this.dataShowDriverCode
      }
       caRuleDriverApi.exportFile(params).then((response) => {
             if (response) {
            console.log(response,'response205')
            var filename = decodeURI(response.headers['content-disposition']).split('=')[1];
            //  var filename = "分摊动因数据展示.xlsx"
            var blob = new Blob([response.data],{
              type: "application/vnd.ms-excel;charset=utf-8"
            }
             );
            if (window.navigator.msSaveOrOpenBlob) {
              navigator.msSaveBlob(blob,filename);
            } else {
              var downloadElement = document.createElement("a");
              var href = window.URL.createObjectURL(blob); //创建下载的链接
              downloadElement.href = href;
              downloadElement.download = filename; //下载后文件名
              document.body.appendChild(downloadElement);
              downloadElement.click(); //点击下载
              document.body.removeChild(downloadElement); //下载完成移除元素
              window.URL.revokeObjectURL(href); //释放掉blob对象
            }
          }
          else{
          this.$message.error(res.message || '获取失败');
        }
            })

    },
    // 静因表格导出
    exportStaticFiles(){
       let params = {
        driverCode: this.dataShowDriverCode,
        sqlOnly: "1",
	      tableName: "STATIC_DRIVER_DATA"
      }
       caRuleDriverApi.exportStaticFile(params).then((response) => {
             if (response) {
            console.log(response,'response20555555')
            var filename = decodeURI(response.headers['content-disposition']).split('=')[1];
            //  var filename = "分摊静因数据展示.xls"
            var blob = new Blob([response.data],{
              type: "application/vnd.ms-excel;charset=utf-8"
              // "multipart/form-data;application/x-xls;charset=utf-8"
              //  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            }
             );
            if (window.navigator.msSaveOrOpenBlob) {
              navigator.msSaveBlob(blob,filename);
            } else {
              var downloadElement = document.createElement("a");
              var href = window.URL.createObjectURL(blob); //创建下载的链接
              downloadElement.href = href;
              downloadElement.download = filename; //下载后文件名
              document.body.appendChild(downloadElement);
              downloadElement.click(); //点击下载
              document.body.removeChild(downloadElement); //下载完成移除元素
              window.URL.revokeObjectURL(href); //释放掉blob对象
            }
          }
          else{
          this.$message.error(res.message || '获取失败');
        }
            })

    },
    checkListInit() {
      this.checkList = this.textData.map(v => {
        return v.label;
      });
    },
    searchFunc() {
      let dataSearch = this.searchForm;
      console.log(dataSearch, "动因新增");
      caRuleDriverApi.ruleDriverQuery(dataSearch).then(res => {
        if (res.code === 200) {
          this.tableData = res.datas.rows;
          this.total = res.datas.total;
          console.log(res.datas,"1111111111111111111111111");
        }
      });
    },
     rowClick(row){
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }
      this.$refs.multipleTable.toggleRowSelection(row, true);
    },
    //删除数据
    deleFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择数据进行删除");
      }
      let delData = { ids: selection.map(v => v.driverCode) };

      caRuleDriverApi.ruleDrivercheckIsRemove(delData).then(res => {
        if (null == res.data || "" == res.data) {
          this.$confirm("你确定要删除选中的分摊动因吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              caRuleDriverApi.ruleDriverDelete(delData).then(res => {
                if (res.code == 200) {
                  this.$message.success("删除成功");
                  this.searchFunc();
                }
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除"
              });
            });
        } else {
          return this.$message.warning(res.data + "被规则引用不可删除");
        }
      });
    },
    //查看引用情况
    refFunc() {
      let selected = this.$refs.multipleTable.selection;
      if (selected.length != 1) {
        return this.$message.warning("请选择一条数据进行查看");
      }
      this.refFalg = true;
     
      this.refdriverCode = selected[0].driverCode;
      console.log(selected[0].driverCode, "引入code1");
      this.refsearchFunc();
      //查询展示情况
    },
    timeFormat(val) {
      if (val) return moment(val).format("YYYY-MM-DD hh:mm:ss");
      else return "-";
    },
    handleSizeChange(val) {
      this.searchForm.size = val;
      this.searchFunc();
      console.log(val, "每页数");
    },
    handleCurrentChange(val) {
      this.searchForm.page = val;
      this.searchFunc();
      console.log(val, "当前页");
    },
    //规则引入
    refhandleSizeChange(val) {
      this.refsearchForm.size = val;
      console.log(val, "ref每页数");
    },
    refhandleCurrentChange(val) {
      this.refsearchForm.page = val;
      console.log(val, "ref当前页");
    },
    refsearchFunc() {
      let refdataSearch = this.refsearchForm;
      refdataSearch.driverCode = this.refdriverCode;
      console.log(refdataSearch, "规则引入");
      caRuleDriverApi.ruleDriverRef(refdataSearch).then(res => {
        if (res.code === 200) {
          this.refTableData = res.data.rows;
          this.reftotal = res.data.total;
          console.log(res.data.rows, "ref当前页");
          this.tabPaneName = "规则引用(" + this.reftotal + ")";
        }
      });
      //对表格进行重新渲染 表格错位问题
      this.$nextTick(() => {
        this.$refs.refmultipleTable.doLayout();
      });
    },
    //弹窗组件方法
    clickBtn(val) {
      let selected = {};
      //判断是否是新增
      if (val != "1") {
        let selectedList = this.$refs.multipleTable.selection;
        //不是新增必须选择一条数据
        if (selectedList.length != 1) {
          this.$message.warning("请选择一条动因数据!");
          return;
        }
        selected = selectedList[0];
        console.log(selected, "生成编码");
      } else {
        //新增 给动因类型 默认值
        this.$set(selected, "driverType", "1");
      }
      //查询获取编码信息
      let _this = this;
      if (val === "1" || val === "5") {
        pubSysparamList.createBizCode({ prefix: "CA_DRIVER" }).then(res => {
          if (res.code == 200 && res.success) {
            let driverCode = res.data;
            if (val == "5") {
              _this.$set(selected, "copyCode", res.data);
            } else if (val == "1") {
              _this.$set(selected, "driverCode", res.data);
            }
            _this.popupWindowType = val;
            _this.dialogVisible = true;
            _this.editTheData = selected;

            // setTimeout(() => {
            //   _this.$refs.ruleDriverForm.init();
            // }, 10);
              this.$nextTick(()=>{
               this.$refs.ruleDriverForm.init();
             })
          } else {
            _this.$message.warning("生成编码出错!");
            return;
          }
        });
      } else {
        this.editTheData = selected;
        this.popupWindowType = val;
        this.dialogVisible = true;
        // setTimeout(() => {
        //   _this.$refs.ruleDriverForm.init();
        // }, 10);
        this.$nextTick(()=>{
          this.$refs.ruleDriverForm.init();
        })
        
      }
    },
    getDialogVisible(val) {
      this.dialogVisible = val;
      this.searchFunc();
    },
    //字典转换
    dictFormatter(row) {
      if (row.driverType == "0") {
        return "静态动因";
      } else if (row.driverType == "1") {
        return "动态动因";
      }
    },
    refDictFormatter(row){
      if (row.driverType == "S") {
        return "静态比例";
      } else if (row.driverType == "D") {
        return "动态比例";
      }
    },
    refRuleTypeFormatter(row){
         if (row.ruleType == "0") {
        return "机构层级";
      } else if (row.ruleType == "1") {
        return "账户层级";
      }
    },
    //############# 引用情况 ######################
    //引用情况
    addOrEditFunc(val) {
      this.buttonType = "3";
      let selection = this.$refs.refmultipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行查看");
      }
      let row = selection[0];
      this.ruleCodeDef = row.ruleCode;
      this.addOrEdit = true;
      // setTimeout(() => {
      //   this.$refs.childComponents.showTabInit();
      // }, 10);
        this.$nextTick(()=>{
          this.$refs.childComponents.showTabInit();
        })
    },
      refRowClick(row){
      if (this.$refs.refmultipleTable) {
        this.$refs.refmultipleTable.clearSelection();
      }
      this.$refs.refmultipleTable.toggleRowSelection(row, true);
    },
    closeToQuery(val) {
      this.addOrEdit = false;
    },
    // ######## 数据展示########
     // 点击表格行事件
     dataShow(){
       let selectList  = this.$refs.multipleTable.selection;
       if(selectList.length != 1){
         this.$message.warning("请选择一条进行数据展示");
         return;
       }
       // 判断该数据时动态还是静态
       let selected = selectList[0];
       //1:动态分摊 0 静态分摊
       if(selected.driverType == "1"){
         this.dataShowView = true;
         this.dataShowDriverCode = selected.driverCode;
         this.queryListDataShow();
       }
       // 静态分摊
       if(selected.driverType == "0"){
         this.xJson = []
         this.yJson = []
         this.tableValue = []
         this.dataShowStaticView = true;
         this.dataShowDriverCode = selected.driverCode;
         this.queryListStaticDataShow();
       }

     },
    dataShowRowClick(row){
      if (this.$refs.dataShowMultipleTable) {
        this.$refs.dataShowMultipleTable.clearSelection();
      }
      this.$refs.dataShowMultipleTable.toggleRowSelection(row, true);
    },
      // 展示字段
    showDataList() {
      let columnEnlist = this.dataShowData.map(v=>{
          return v.columnEn.toUpperCase();
      })
       this.$set(this.dataShowSearchForm,"cloumnList",columnEnlist);
        this.$set(this.dataShowSearchForm,"driverCode",this.dataShowDriverCode);
     
        console.log(this.dataShowData,"数据展查询条件")
      caRuleDriverApi.ruleDriverShowDataBaseDriver(this.dataShowSearchForm).then(res=>{
        if(res.code == 200){
          this.dataShowTableList = res.datas.rows; 
          this.dataShowTotal = res.datas.total;
        }
      })
  
    },
    queryListDataShow(){
          //查询金融工具表展示数据  
         caRuleDriverApi.ruleDriverfindTableEn({driverCode:this.dataShowDriverCode}).then(res =>{
           if(res.code == 200){
             //根据表名查询字段维度 
                    let params = {
                      driverCode:this.dataShowDriverCode,
                      tablenameEn:res.data,
                    }
                   caRuleDriverApi.ruleDriverfindColumnsEn(params).then(res =>{
                      if(res.code == 200){
                          //获取到展示的字段值 
                          this.dataShowData =  res.datas;
                          this.showDataList();
                      }

                   })
                   .catch(err =>{
                     console.log(err);
                   })           }
         })
         .catch(err =>{
           console.log(err);
         })
    },
    // 获取静态因子展示数据
    queryListStaticDataShow(){
      let params = {
         driverCode:this.dataShowDriverCode
      }
       caRuleDriverApi.ruleDriverfindStaticDataCode(params).then(res => {
        if (res.code === 200) {
          // this.tableData = res.datas.rows;
          // this.total = res.datas.total;
          this.xJson = res.datas.driverDataXJson
          this.yJson = res.datas.driverDataYJson
          this.tableValue = res.datas.tableValue
          // 构造表格
          this.toGetGenerateTable()
        } else{
          this.$message.error(res.message || "获取失败")
        }
      });
    },
    toGetGenerateTable(){
       this.ctableShow =true
    },
    dataShowSearchFunc(){
        this.queryListDataShow();
    },
    dataShowhandleSizeChange(val){
      this.dataShowSearchForm.size = val
      this.showDataList();
      console.log(val,"展示数据量");
    },
    dataShowhandleCurrentChange(val){
       this.dataShowSearchForm.page = val
        this.showDataList();
      console.log(val,"引用当前页");
    }
  } //方法结束
};
</script>
                    
<style lang="scss" scoped>
</style>
